﻿using Back_end.Models;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Threading.Tasks;
using System.Web.Http;
using System.Web.Http.Cors;
using System.Web.Http.Description;

namespace Back_end.APIControllers
{
	// [Authorize]
	[RoutePrefix("api/Companies")]
	[EnableCors("*", "*", "*")]
	public class CompaniesApiController : ApiController
    {
        private ApplicationDbContext db = new ApplicationDbContext();

        // GET: api/Companies
        public IQueryable<Company> GetCompanies()
        {
            return db.Companies;
        }

        // GET: api/Companies/5
        [ResponseType(typeof(Company))]
		[Route("Get")]
        public async Task<IHttpActionResult> GetCompany(string id)
        {
            Company company = await db.Companies.FindAsync(id);
            if (company == null)
            {
                return NotFound();
            }

            return Ok(company);
        }

		[ResponseType(typeof(Company))]
		[Route("GetAroundByCoor")]
		public IHttpActionResult GetCompanyByCoordiante(string coor)
		{
			var cs = coor.Split(',');
			Tuple<double, double> coordiante =
				new Tuple<double, double>(Double.Parse(cs[0]), Double.Parse(cs[1]));

			var companies = new List<Company>();
			foreach (var c in db.Companies)
			{
				var temps = c.Coordinates.Split(',');
				var temp = new Tuple<double, double>(Double.Parse(temps[0]), Double.Parse(temps[1]));
				if (temp.Item1 <= coordiante.Item1 - 0.01
							&& coordiante.Item1 + 0.01 <= temp.Item1
							&& temp.Item2 <= coordiante.Item2 - 0.01
							&& coordiante.Item2 + 0.01 <= temp.Item2)
					companies.Add(c);
			}

			return Ok(companies);
		}

		[Route("Search")]
		public IHttpActionResult GetCompanyByName(string name)
		{
			var list = from c in db.Companies
					   where c.Name.Contains(name)
					   select c;

			if (list == null || list.Count() == 0)
				return NotFound();

			return Ok(list);
		}

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                db.Dispose();
            }
            base.Dispose(disposing);
        }

        private bool CompanyExists(string id)
        {
            return db.Companies.Count(e => e.Name == id) > 0;
        }
    }
}